import 'dart:io';

import 'package:baselib/utils/num_util.dart';
import 'package:flutter/material.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/select_photo_camera_alert_widget.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';

class ImgPickUtil {
  static final ImgPickUtil _singleton = ImgPickUtil._internal();

  static ImgPickUtil get instance => ImgPickUtil();

  factory ImgPickUtil() {
    return _singleton;
  }

  ImgPickUtil._internal() {
    _picker = ImagePicker();
  }

  // 图片选择器
  late ImagePicker _picker;

  /**
   * 选择单图
   */
  Future<XFile?> pickImg() async {
    print("选择图片,_picker-->${_picker}");
    SelectedType? value = await showModalBottomSheet(
        context: Get.context!,
        builder: (_) {
          return SelectPhotoOrCameraAlertWidget();
        });
    ImageSource imageSource = (value == SelectedType.SelectedCameraType
        ? ImageSource.camera
        : ImageSource.gallery);
    final pickedFile = await _picker?.pickImage(source: imageSource,imageQuality: 100);
    return pickedFile;
  }

  Future<List<XFile>?> pickImgs({int? maxImgNum}) async {
    print("选择图片,_picker-->${_picker}");
    final pickedFiles = await _picker?.pickMultiImage(
       limit: 9,
       requestFullMetadata: false
    );
    return pickedFiles;
  }



  ///裁切图片
  ///[image] 图片路径或文件
  ///[width] 宽度
  ///[height] 高度
  ///[aspectRatio] 比例
  ///[androidUiSettings]UI 参数
  ///[iOSUiSettings] ios的ui 参数
  Future<CroppedFile?> cropImage(
      {required image,
        required width,
        required height,
        int? compressQuality,
        aspectRatio,
        androidUiSettings,
        iOSUiSettings}) async {
    String imagePth = "";
    if (image is String) {
      imagePth = image;
    } else if (image is File) {
      imagePth = image.path;
    } else {
      throw ("文件路径错误");
    }
    final croppedFile = await ImageCropper().cropImage(
      sourcePath: imagePth,
      maxWidth: NumUtil.num2int(width),
      maxHeight: NumUtil.num2int(height),
      compressQuality: compressQuality??100,
      aspectRatio: aspectRatio ??
          CropAspectRatio(
              ratioX: NumUtil.num2double(width),
              ratioY: NumUtil.num2double(height)),
      uiSettings: [
        androidUiSettings ??
            AndroidUiSettings(
                toolbarTitle:
                // '${string_cropper}(${NumUtil.num2int(width)}*${NumUtil.num2int(height)})',
                '${string_cropper}',
                toolbarColor: Colors.blue,
                toolbarWidgetColor: Colors.white,
                initAspectRatio: CropAspectRatioPreset.original,
                hideBottomControls: false,
                lockAspectRatio: true),
        iOSUiSettings ??
            IOSUiSettings(
              title: '${string_cropper}',
            ),
      ],
    );
    return croppedFile;
  }


}
